//
//  SQLManager.swift
//  FMDB
//
//  Created by  郭航 on 16/7/8.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

private let dataBaseName: String = "dataBase.db"

class SQLManager {

    static let shareManager: SQLManager = SQLManager()
    
    let dataBase: FMDatabaseQueue
    
    private init() {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dataBaseName)
        dataBase = FMDatabaseQueue(path: path)
        
        createTabel()
    }
    
    private func createTabel() -> Void {
        let path = NSBundle.mainBundle().pathForResource("dataBase", ofType: "db")!
        let sqlStr = try! String(contentsOfFile: path)
        
        dataBase.inDatabase { (db) in
            if !db.executeStatements(sqlStr) {
                print("创建表失败")
            }
        }
    }
    
    func selectAll(sqlStr: String) -> [[String : AnyObject]] {
        var result: [[String : AnyObject]] = [[String : AnyObject]]()
        
        dataBase.inDatabase { (db) in
            let resultSet = db.executeQuery(sqlStr, withArgumentsInArray: nil)
            
            while resultSet.next() {
                var dic: [String : AnyObject] = [String : AnyObject]()
                
                for i in 0 ..< resultSet.columnCount() {
                    let key = resultSet.columnNameForIndex(i)
                    let value = resultSet.objectForColumnIndex(i)
                    
                    dic[key] = value
                }
                result.append(dic)
            }
        }
        return result
    }
    
}
